package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/*
货物模块
 */
@Controller
@RequestMapping("/cargo/contractProduct")
@Slf4j
public class ContractProductController extends BaseController {
    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /*
    进入货物列表页面
     */
    @RequestMapping("/list")
    public String list(String contractId,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行查询购销合同的货物列表:");
        //构造条件对象
        ContractProductExample example = new ContractProductExample();
        ContractProductExample.Criteria criteria = example.createCriteria();
        //条件一（设置购销合同id）
        criteria.andContractIdEqualTo(contractId);
        //条件二(设置企业id)
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        //根据企业id和购销合同id查询货物信息
        PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(example, pageNum, pageSize);

        //查询所有的生产厂家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryCriteria = factoryExample.createCriteria();
        factoryCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);


        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("contractId", contractId);
        request.setAttribute("factoryList", factoryList);
        return "cargo/product/product-list";
    }

    /*
    货物添加/修改
     */
    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        //设置企业信息
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());


        if (StringUtils.isEmpty(contractProduct.getId())) {
            /*处理文件上传到七牛云*/
            try {
                String imgUrl = "http://" + fileUploadUtil.upload(productPhoto);
                contractProduct.setProductImage(imgUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            contractProductService.save(contractProduct);
        } else {
            //有购销合同id,执行更新
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list?contractId=" + contractProduct.getContractId();
    }


    //cargo/contractProduct/toUpdate.do?id=${o.id}
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        //查询所有的生产厂家
        //创建厂家条件对象
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryCriteria = factoryExample.createCriteria();
        //设置条件
        factoryCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //回显厂家下拉列表数据
        request.setAttribute("factoryList", factoryList);

        //根据货物id查询货物数据
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);

        return "cargo/product/product-update";
    }

    //cargo/contractProduct/delete.do
    //删除货物
    @RequestMapping("/delete")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId=" + contractId;
    }

    //进入货物上传页面 /cargo/contractProduct/toImport.do
    @RequestMapping("/toImport")
    public String toImport(String contractId) {
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-import";
    }


    //导入货物（excel文件）
    ///cargo/contractProduct/import.do
    @RequestMapping("/import")
    public String importExport(String contractId, MultipartFile file) throws IOException {
        //根据excel文件流创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        
        //获取工作表
        XSSFSheet sheet = workbook.getSheetAt(0);

        //获取总行数
        int rows = sheet.getPhysicalNumberOfRows();

        //遍历每一行，从第二行开始
        for (int i = 1; i < rows; i++) {
            //获取每一行
            XSSFRow row = sheet.getRow(i);
            
            //创建货物对象
            ContractProduct cp = new ContractProduct();
            cp.setFactoryName(row.getCell(1).getStringCellValue());
            cp.setProductNo(row.getCell(2).getStringCellValue());
            cp.setCnumber((int) row.getCell(3).getNumericCellValue());
            cp.setPackingUnit(row.getCell(4).getStringCellValue());
            cp.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
            cp.setBoxNum((int) row.getCell(6).getNumericCellValue());
            cp.setPrice(row.getCell(7).getNumericCellValue());
            cp.setProductDesc(row.getCell(8).getStringCellValue());
            cp.setProductRequest(row.getCell(9).getStringCellValue());
            //设置购销合同id
            cp.setContractId(contractId);

            Factory factory = factoryService.findByFactoryName(cp.getFactoryName());
            if(factory !=null){
                cp.setFactoryId(factory.getId());
            }

            //设置企业信息
            cp.setCompanyId(getLoginCompanyId());
            cp.setCompanyName(getLoginCompanyName());

            contractProductService.save(cp);
        }
        return "redirect:/cargo/contractProduct/list?contractId=" + contractId;
    }


}
